% Function for the RHs of the firskt order condtionsk

function rhs=rbcrhs(x);

% SET PARAMETER VALUES
global beta;
global deltaeq;
global deltas;
global gamma;
global alfa;
global sk;
global u;
global ws;
global wu;
global req;
global rs;
global y;
global sigma;
global ph;
global mu;
global lambda;
global weight;
global rhoaa;
global rhoap;
global rhopp;
global rhopa;
global ksshare;
global thetak;
global thetau;
global thetas;
global ces;

% intermediate functions - useful to easy the notation 
% net interest rate - wage - prod.fcn. - marg.util.cons. - marg.util.lab 
% XSS=ke,ks,z,q,hs,hu,cs,cu


if ces == 1;
   ws=exp(x(3))*x(2)^ksshare*(mu*(u*x(6))^sigma+(1-mu)*((1-lambda)*(sk*x(5))^ph+lambda*x(1)^ph)^(sigma/ph))^((1-ksshare-sigma)/sigma)*...
      (1-ksshare)*(1-mu)*((1-lambda)*(sk*x(5))^ph+lambda*x(1)^ph)^((sigma-ph)/ph)*(1-lambda)*(sk*x(5))^(ph-1);
   wu=exp(x(3))*x(2)^ksshare*(mu*(u*x(6))^sigma+(1-mu)*((1-lambda)*(sk*x(5))^ph+lambda*x(1)^ph)^(sigma/ph))^((1-ksshare-sigma)/sigma).*...
      (1-ksshare)*mu*(u*x(6))^(sigma-1);
   y=exp(x(3))*x(2)^ksshare*(mu*(u*x(6))^sigma+(1-mu)*((1-lambda)*(sk*x(5))^ph+lambda*x(1)^ph)^(sigma/ph))^((1-ksshare)/sigma);
   rs=exp(x(3))*ksshare*x(2)^(ksshare-1)*(mu*(u*x(6))^sigma+(1-mu)*(lambda*x(1)^ph+(1-lambda)*(sk*x(5))^ph)^(sigma/ph))^((1-ksshare)/sigma);
   req=exp(x(3))*x(2)^ksshare*((1-ksshare)/sigma)*(mu*(u*x(6))^sigma+(1-mu)*(lambda*x(1)^ph+(1-lambda)*(sk*x(5))^ph)^(sigma/ph))^((1-ksshare-sigma)/sigma)*(1-mu)*sigma*...
      (lambda*x(1)^ph+(1-lambda)*(sk*x(5))^ph)^((sigma-ph)/ph)*lambda*x(1)^(ph-1);
else;
   y = exp(x(3))*x(2)^ksshare*x(1)^thetak*(sk*x(5))^thetas*(u*x(6))^thetau;
   ws = thetas*exp(x(3))*x(2)^ksshare*x(1)^thetak*(sk*x(5))^(thetas-1)*(u*x(6))^thetau;
   wu = thetau*exp(x(3))*x(2)^ksshare*x(1)^thetak*(sk*x(5))^thetas*(u*x(6))^(thetau-1);
   req = thetak*exp(x(3))*x(2)^ksshare*x(1)^(thetak-1)*(sk*x(5))^thetas*(u*x(6))^thetau;
   rs = ksshare*exp(x(3))*x(2)^(ksshare-1)*x(1)^thetak*(sk*x(5))^thetas*(u*x(6))^thetau;
end;

mucu=(1-weight)*u*(x(8)^alfa*(1-x(6))^(1-alfa))^(-gamma)*alfa*x(8)^(alfa-1)*(1-x(6))^(1-alfa);
mucs=weight*sk*(x(7)^alfa*(1-x(5))^(1-alfa))^(-gamma)*alfa*x(7)^(alfa-1)*(1-x(5))^(1-alfa);
munu=(1-weight)*u*(x(8)^alfa*(1-x(6))^(1-alfa))^(-gamma)*(1-alfa)*(1-x(6))^(-alfa)*(-1)*x(8)^alfa;
muns=weight*sk*(x(7)^alfa*(1-x(5))^(1-alfa))^(-gamma)*(1-alfa)*(1-x(5))^(-alfa)*(-1)*x(7)^alfa;

% Order: keq,ks,z,q,hs,hu,cs,cu

rhs=zeros(8,1);
rhs(1)=-sk*x(7)-u*x(8)+(1-deltaeq)*x(1)/exp(x(4))+(1-deltas)*x(2)+y;
rhs(2)=rhoaa*x(3);
rhs(3)=rhopp*x(4);
rhs(4)=muns + mucs*sk*ws;
rhs(5)=munu + mucu*u*wu;
rhs(6)=mucs - mucu;
rhs(7)=mucu/exp(x(4));
rhs(8)=mucu;